<template>
  <div class="app-container">

    <!--查询条件-->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="设备编码">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入设备编码"
          clearable
          style="width: 240px"
          @keyup.enter.native="getListByPage()"
        />

      </el-form-item>
      <el-form-item label="设备名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="getListByPage()"
        />

      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="设备状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in equipmentStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getListByPage()">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetData()">重置</el-button>
      </el-form-item>
    </el-form>

    <!--操作按钮-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="batchDeleteEquipment()"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="showAdd()"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-view"
          size="mini"
          @click="showEquipmentTypeDialog()"
        >查看设备类型</el-button>
      </el-col>
    </el-row>

    <!--表格开始-->
    <el-table
      v-loading="loading"
      :data="dataList"
      :header-cell-style="{background:'#F8F8F9'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        type="index"
        label="序号"
        width="50"
      />
      <el-table-column label="设备编码" align="center" prop="code" />
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="设备状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="changeStatus($event, scope.row, scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" prop="equipmentTypeName" />
      <el-table-column label="设备描述" align="center" prop="equipmentTypeDescription" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            title="修改"
            @click="showEdit(scope.row.id)"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            title="删除"
            @click="deleteEquipment(scope.row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--表格开始-->

    <!-- 分页组件 -->
    <el-pagination
      v-if="total > 0"
      :total="total"
      :current-page.sync="queryParams.current"
      :page-size.sync="queryParams.pageSize"
      :page-sizes="[1,2, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      style="padding: 30px 0; text-align: center;"
      @current-change="getListByPage(queryParams.current)"
      @size-change="handleSizeChange"
    />

    <!-- 弹出框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40">
      <el-form ref="dataForm" :model="equipment" label-width="100px" size="small" style="padding-right: 40px;">

        <el-form-item label="设备类型" prop="equipmentTypeId">
          <el-select
            v-model="equipment.equipmentTypeId"
            placeholder="请选择设备类型"
            :filterable="true"
          >
            <el-option
              v-for="item in equipmentTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备编码" prop="name">
          <el-input v-model="equipment.code" />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="equipment.name" />
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="equipment.status" size="medium" @change="$forceUpdate()">
            <el-radio border :label="0">关闭</el-radio>
            <el-radio border :label="1">开启</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-refresh-right" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" size="small" @click="saveOrUpdate()">确 定</el-button>
      </span>
    </el-dialog>

    <!--设备类型 开始-->

    <!--设备类型-->
    <el-dialog title="设备类型" :visible.sync="showEquipmentTypeVisible" width="60%" center>

      <!--设备类型操作按钮-->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="batchDeleteEquipmentType()"
          >批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="showAddEquipmentType()"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="showEditEquipmentType()"
          >修改</el-button>
        </el-col>
      </el-row>
      <!--设备类型表格-->
      <el-table
        ref="multipleTable"
        :data="equipmentTypeList"
        :header-cell-style="{background:'#F8F8F9'}"
        @selection-change="handleSelectionChangeEquipmentType"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          type="index"
          label="序号"
          width="50"
        />
        <el-table-column property="name" label="设备名称" />
        <el-table-column property="description" label="设备描述" />
        <el-table-column property="createTime" label="创建时间" />
      </el-table>
    </el-dialog>

    <!-- 设备类型弹出框 -->
    <el-dialog :title="equipmentTypeDialogTitle" :visible.sync="operationDialogVisible" width="40">
      <el-form ref="dataForm" :model="equipmentType" label-width="100px" size="small" style="padding-right: 40px;">
        <el-form-item label="设备类型" prop="name">
          <el-input v-model="equipmentType.name" />
        </el-form-item>
        <el-form-item label="设备描述">
          <el-input v-model="equipmentType.description" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-refresh-right" @click="operationDialogVisible = false">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" size="small" @click="saveOrUpdateEquipmentType ()">确 定</el-button>
      </span>
    </el-dialog>

    <!--设备类型 结束-->

  </div>
</template>

<script>
import api from '@/api/hardware/equipment/equipment'
import equipmentTypeApi from '@/api/hardware/equipment/equipmentType'

export default {
  name: 'Equipment',
  data() {
    return {
      loading: true,
      dataList: [], // 表格数据
      equipment: {}, // 设备对象
      total: 0, // 总记录数
      queryParams: {
        current: 1, // 页码
        pageSize: 20, // 每页记录数
        code: '',
        name: '',
        status: '',
        equipmentTypeId: ''
      },
      // 多选
      multipleSelection: [],
      dialogVisible: false,
      dialogTitle: '',
      // 设备状态下拉列表
      equipmentStatusList: [
        {
          value: '0',
          label: '关闭'
        },
        {
          value: '1',
          label: '打开'
        }],

      // 设备类型列表
      equipmentTypeList: [],
      // 设备类型
      equipmentType: {},
      // 显示设备类型
      showEquipmentTypeVisible: false,
      // 显示设备类型添加修改操作弹出框
      operationDialogVisible: false,
      // 设备类型标题
      equipmentTypeDialogTitle: '',
      multipleSelectionEquipmentType: []

    }
  },
  beforeMount() {
    this.getListByPage()
    this.getEquipmentTypeList()
  },
  methods: {

    /**
     * 显示设备类型
     */
    showEquipmentTypeDialog() {
      this.showEquipmentTypeVisible = true
      this.$refs.multipleTable.clearSelection()
    },

    /**
     * 更改设备状态
     *
     * @param e
     * @param row
     * @param index
     */
    async changeStatus(e, row, index) {
      // e返回状态，row当前行数据，index下标
      // console.log(e, row, index)
      await api.changeEquipmentStatus(row.id, row.status)
      // this.$message.success(res.message || '恭喜，修改状态操作成功！')
    },

    /**
     * 弹出添加的表单
     */
    showAdd() {
      this.dialogTitle = '新建设备'
      this.dialogVisible = true
      this.equipment = {}
    },

    /**
     * 弹出编辑的表单
     *
     * @param id
     */
    async showEdit(id) {
      this.dialogTitle = '编辑设备'
      this.dialogVisible = true
      this.equipment = {}
      const res = await api.getEquipmentById(id)
      this.equipment = res.data
    },

    /**
     * 发送添加或更新请求
     */
    saveOrUpdate() {
      if (!this.equipment.id) {
        this.addEquipment()
      } else {
        this.updateEquipment()
      }
    },

    /**
     * 创建设备
     */
    async addEquipment() {
      try {
        this.loading = true
        const res = await api.addEquipment(this.equipment)
        this.$message.success(res.message || '恭喜，添加操作成功！')
        this.dialogVisible = false
        await this.getListByPage(this.queryParams.current)
      } finally {
        this.loading = false
      }
    },

    /**
     * 删除设备
     *
     * @param id
     */
    deleteEquipment(id) {
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // TODO 删除最后一个有bug
        const res = await api.deleteEquipment(id)
        await this.getListByPage(this.queryParams.current)
        this.$message.success(res.message || '恭喜，删除操作成功！')
      }).catch()
    },

    // 当多选选项发生变化的时候调用
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },

    /**
     * 批量删除
     */
    batchDeleteEquipment() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const idList = []
        this.multipleSelection.forEach(equipment => { idList.push(equipment.id) })
        const res = await api.batchDeleteEquipment(idList)
        // TODO 是否要跳到当前页
        await this.getListByPage(this.queryParams.current)
        this.$message.success(res.message || '恭喜，批量删除操作成功！')
      }).catch()
    },

    /**
     * 更新设备
     */
    async updateEquipment() {
      const res = await api.updateEquipment(this.equipment)
      this.$message.success(res.message || '恭喜，修改操作成功！')
      this.dialogVisible = false
      await this.getListByPage(this.current)
    },

    /**
     * 重置查询表单
     */
    resetData() {
      this.queryParams.code = null
      this.queryParams.name = null
      this.queryParams.status = null
      this.getListByPage()
    },

    /**
     * 每页大小发生变化的回调
     *
     * @param pageSize
     */
    handleSizeChange(size) {
      console.log(this.queryParams.pageSize)
      this.queryParams.pageSize = size
      this.getListByPage()
    },

    /**
     * 分页查询
     *
     * @returns {Promise<void>}
     */
    async getListByPage(pageNum = 1) {
      try {
        this.queryParams.current = pageNum
        const res = await api.listEquipmentByPage(this.queryParams)
        this.dataList = res.data.records
        this.total = res.data.total
        this.queryParams.current = res.data.current
        this.queryParams.pageSize = res.data.size
      } finally {
        this.loading = false
      }
    },

    // 下面是设备类型方法

    /**
     * 弹出设备类型添加的表单
     */
    showAddEquipmentType() {
      this.equipmentTypeDialogTitle = '新建设备类型'
      this.operationDialogVisible = true
      this.equipmentType = {}
    },

    /**
     * 弹出设备类型编辑的表单
     *
     * @param id
     */
    async showEditEquipmentType() {
      console.log(this.multipleSelectionEquipmentType.length)
      if (this.multipleSelectionEquipmentType.length === 0) {
        this.$message.warning('请选择要修改的数据！')
        return
      }
      if (this.multipleSelectionEquipmentType.length > 1) {
        this.$message.warning('请选择一条修改的数据！')
        return
      }
      this.equipmentTypeDialogTitle = '编辑设备类型'
      this.operationDialogVisible = true
      this.equipmentType = {}
      const id = this.multipleSelectionEquipmentType[0].id
      const res = await equipmentTypeApi.getEquipmentTypeById(id)
      this.equipmentType = res.data
    },

    /**
     * 设备类型发送添加或更新请求
     */
    saveOrUpdateEquipmentType() {
      if (!this.equipmentType.id) {
        this.addEquipmentType()
      } else {
        this.updateEquipmentType()
      }
    },

    /**
     * 创建设备类型
     */
    async addEquipmentType() {
      const res = await equipmentTypeApi.addEquipmentType(this.equipmentType)
      this.$message.success(res.message || '恭喜，添加操作成功！')
      this.operationDialogVisible = false
      await this.getEquipmentTypeList()
    },

    /**
     * 批量删除
     */
    batchDeleteEquipmentType() {
      if (this.multipleSelectionEquipmentType.length === 0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const idList = []
        this.multipleSelectionEquipmentType.forEach(equipmentType => { idList.push(equipmentType.id) })
        const res = await equipmentTypeApi.batchDeleteEquipmentType(idList)
        // TODO 是否要跳到当前页
        await this.equipmentTypeList()
        this.$message.success(res.message || '恭喜，批量删除操作成功！')
      }).catch()
    },

    /**
     * 更新设备
     */
    async updateEquipmentType() {
      const res = await equipmentTypeApi.updateEquipmentType(this.equipmentType)
      this.$message.success(res.message || '恭喜，修改操作成功！')
      this.operationDialogVisible = false
      await this.getEquipmentTypeList()
    },

    // 设备类型多选回调处理
    handleSelectionChangeEquipmentType(selection) {
      this.multipleSelectionEquipmentType = selection
    },

    /**
     * 获取所有设备类型信息
     *
     * @returns {Promise<void>}
     */
    async getEquipmentTypeList() {
      const res = await equipmentTypeApi.listEquipmentType()
      this.equipmentTypeList = res.data
    }

  }

}
</script>

<style scoped>

</style>
